package com.xm.algorithm;

/**
 * 二分查找是一种高效的查找算法，适用于已排序的数组。
 * 它通过将查找区间一分为二，
 * 逐步缩小查找范围，
 * 直到找到目标元素或确定目标元素不存在。
 */
public class BinarySearch {
    public static void main(String[] args) {
        int[] arr = {11, 12, 22, 25, 34, 64, 90};
        System.out.println(methodFor(arr, 22));

        System.out.println(methodRecursion(arr, 22, 0, arr.length));
    }

    /**
     * 利用for循环实现
     */
    public static int methodFor(int[] arr, int target) {
        int left = 0;
        int right = arr.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (arr[mid] == target) {
                return mid;
            } else if (arr[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return -1;
    }

    /**
     * 利用recursion递归实现
     */
    public static int methodRecursion(int[] arr, int target, int left, int right) {
        if (left > right) {
            return -1;
        }
        int mid = left + (right - left) / 2;
        if (arr[mid] == target) {
            return mid;
        } else if (arr[mid] < target) {
            return methodRecursion(arr, target, mid + 1, right);
        } else {
            return methodRecursion(arr, target, left, mid - 1);
        }
    }
}
